package com.chat.socketservice;

/**
 * Created by shirenchuang on 2017/4/3.
 */
import com.chat.room.Room;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 服务器
 * @author Administrator
 *
 */
public class Service {

    private int duankou = 9000;//端口号
    private ServerSocket server;//声明服务器
   // private static Socket socket;//声明客户端
    private String serName;
    private static ConcurrentHashMap<Integer,Room> socketmap =new ConcurrentHashMap<Integer, Room>();
    public Service(){
        try {
            init();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static int creatRoom(){
       //TODO
        Room room = new Room(socketmap.size()+1);
        socketmap.put(room.getRoomid(),room);
        System.out.print("创建房间号："+room.getRoomid());
        return room.getRoomid();
    }

    public static void joinRoom(Integer roomid,Socket socket){
        Room room = socketmap.get(roomid);
        room.getSockets().add(socket);
    }


    /*
     * 创建服务器，开始监听
     */
    private void init() throws IOException{
        creatRoom();
                server = new ServerSocket(duankou);
        System.out.println("------服务器已开启--------");
        System.out.println("请输入服务器名字：");
        Scanner sc = new Scanner(System.in);
        serName = sc.next();
        while(true){
            Socket socket = server.accept();
            hands(socket);
        }
    }


    private void hands(Socket socket) {
        String key = socket.getInetAddress().getHostAddress()+":"+socket.getPort();
        System.out.println("监听到的客户端："+key);
        Thread thread = new Thread(new ThreadSocket(socketmap,socket));
        thread.setName(serName);
        thread.start();
    }

    public static void main(String[] args) {
        Service server = new Service();
    }

}


